<template>
  <div class="app-container" style="margin-left: -20px">
    <el-form :model="sandForm" :rules="rules"  ref="sandForm" label-width="100px" v-loading="formLoading" >
      <el-form-item label="材料：" prop="articleContent" required >
        <el-input
          type="textarea"
          placeholder="请输入内容"
          autosize
          @input="onInput"
          v-model="sandForm.articleContent">
        </el-input>
      </el-form-item>
      <el-form-item label="图片：">
        <el-form-item>
          <div v-for="(item, index) in pictures" :key="index" style="display: flex; align-items: center; margin-bottom: 10px;">
            <el-image :src="item" :preview-src-list="pictures"  style="width: 200px; margin-right: 10px;"></el-image>
            <el-button type="danger" icon="el-icon-delete" circle @click="removePicture(index)"></el-button>
          </div>
        </el-form-item>
        <el-upload
          :action="actionUrl"
          :on-change="handleImageUpload"
          :on-remove="handleImageRemove"
          multiple
          :limit="5"
          :show-file-list="false"
          list-type="picture-card"
          :auto-upload="false"
        >
          <i class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="题干：" v-for="(item,index) in sandForm.textContent" :key="index" required >
        <el-input v-model="item.qtitle" style="width: 80%;"/>
        <el-button type="danger" size="mini" class="question-item-remove" icon="el-icon-delete" @click="questionItemRemove(index)"></el-button>
        <el-form-item label="翻译："  style="margin-left: -100px; margin-top: 20px; width: 87.5%;" >
          <el-input v-model="correctName[index]"   />
        </el-form-item>
      </el-form-item>
      <el-form-item label="解析：" prop="analyze" >
        <el-input v-model="sandForm.analyze"   />
      </el-form-item>
      <el-form-item label="分数：" prop="score" required>
        <el-input-number v-model="sandForm.score" :precision="1" :step="1" :max="100"></el-input-number>
      </el-form-item>
      <el-form-item label="难度：" required>
        <el-rate v-model="sandForm.difficult" class="question-item-rate"></el-rate>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button type="success" @click="questionItemAdd">添加题干</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { mapGetters, mapState, mapActions } from 'vuex'
import questionApi from '@/api/question'
export default {
  props: {
    message: Object
  },
  data () {
    return {

      rules: {
        articleContent: [
          { required: true, message: '材料不能为空', trigger: 'blur' }
        ],
        qtitle: [
          { required: true, message: '题干不能为空', trigger: 'blur' }
        ],
        QTitle: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      },
      correctName: [],
      sandForm: {
        analyze: '',
        id: null,
        questionTypeId: null,
        questionTypeName: '',
        subjectId: null,
        gradeLevel: null,
        subjectParentId: null,
        chapterName: '',
        chapterId: null,
        subjectName: '',
        title: '',
        textContent: [
          {
            qtitle: '',
            item: [
              {
                prefix: '',
                content: ''
              }
            ]
          }
        ],
        status: null,
        articleId: null,
        articleContent: [],
        createUserId: null,
        createUserName: '',
        correct: '',

        createTime: '',
        correctArray: [],
        score: null,
        difficult: null,
        modifyTime: '',
        suggestTime: null,
        picture: '',
        QTitle: ''
      },
      subjectFilter: null,
      formLoading: false,
      richEditor: {
        dialogVisible: false,
        object: null,
        parameterName: '',
        instance: null
      },
      items: [
        {
          prefix: '',
          content: ''
        }
      ],
      actionUrl: '',
      sandFormFile: {
        file: '',
        fileType: 'question'
      },
      url: 'http://localhost:8000/api/uploadPath',
      pictures: []
    }
  },
  created () {
    this.sandForm = this.message
    this.correctName = this.sandForm.correct.split(',')
    this.items = this.sandForm.textContent
    this.pictures = this.sandForm.picture.split(',')
    if (this.pictures[0] === '') {
      this.pictures.splice(0, 1)
    }
  },
  mounted () {
  },
  methods: {
    onInput () {
      this.$forceUpdate()
    },
    removePicture (index) {
      this.pictures.splice(index, 1)
    },
    handleImageUpload (file) {
      this.sandFormFile.file = file
      this.formLoading = true
      const formData = new FormData()
      let data = this.sandFormFile
      for (let key in data) {
        if (data[key] instanceof Array && data[key].length && data[key][0].raw) {
          for (let file of data[key]) {
            formData.append(key, file.raw)
          }
        } else if (data[key] && data[key].raw) {
          formData.append(key, data[key].raw)
        } else {
          formData.append(key, data[key])
        }
      }
      questionApi.uploadFile(formData).then(re => {
        if (re != null) {
          console.log(re)
          console.log(this.pictures)
          this.$message.success('上传成功')
          this.pictures.push(this.url + re)
          this.formLoading = false
        } else {
          this.$message.error('上传失败，请重试')
          this.formLoading = false
        }
      }).catch(e => {
        this.formLoading = false
      })
    },
    handleImageRemove (file, fileList) {
      this.pictures = fileList
    },
    questionItemRemove (index) {
      this.sandForm.textContent.splice(index, 1)
    },
    /**
 * 添加一个新的问题选项
 * 该方法会检查当前选项的前缀，并根据最后一个选项的前缀生成一个新的前缀，然后将新选项添加到 items 数组中
 */
    questionItemAdd () {
      // 在 items 数组中添加一个新的选项，其前缀为新计算出的前缀，内容为空字符串
      this.sandForm.textContent.push({ qtitle: '', item: null })
    },

    submitForm () {
      let _this = this
      this.$refs.sandForm.validate((valid) => {
        if (valid) {
          this.formLoading = true
          this.sandForm.correct = this.correctName.join(',')
          this.sandForm.picture = this.pictures.join(',')
          questionApi.edit(this.sandForm).then(re => {
            if (re.code === 1) {
              _this.$message.success(re.message)
              _this.delCurrentView(_this).then(() => {
                _this.$router.push('/exam/question/list')
              })
            } else {
              _this.$message.error(re.message)
              this.formLoading = false
            }
          }).catch(e => {
            this.formLoading = false
          })
        } else {
          return false
        }
      })
    },
    resetForm () {
      let lastId = this.sandForm.id
      this.$refs['sandForm'].resetFields()
      this.sandForm = {
        id: null,
        questionTypeId: null,
        questionTypeName: '',
        subjectId: null,
        gradeLevel: null,
        subjectParentId: null,
        chapterName: '',
        chapterId: null,
        subjectName: '',
        title: '',
        textContent: [
          {
            qtitle: '',
            item: [
              {
                prefix: '',
                content: ''
              }
            ]
          }
        ],
        status: null,
        articleId: null,
        articleContent: [],
        createUserId: null,
        createUserName: '',
        correctName: [],
        correct: '',
        createTime: '',
        correctArray: [],
        score: null,
        difficult: null,
        modifyTime: '',
        suggestTime: null,
        picture: ''
      }
      this.sandForm.id = lastId
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    ...mapActions('tagsView', { delCurrentView: 'delCurrentView' })
  },
  computed: {
    ...mapGetters('enumItem', ['enumFormat']),
    ...mapState('enumItem', {
      questionTypeEnum: state => state.exam.question.typeEnum
    }),
    ...mapState('exam', { subjects: state => state.subjects })
  }
}
</script>
